<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #screen{
            width: 800px;
            height: 400px;
            background: #0000ff;
        }
    </style>
</head>
<body>
    <div id="screen"></div>
    <input id="message" placeholder="发送弹幕">
    <button id="btn">发送</button>
    <script src="jQuery3.6.0.js"></script>
    <script>
        var websocket = null;
        //浏览器是否支持WebSocket
        if('WebSocket' in window){
            //指定弹幕服务器的ip和端口
            websocket = new WebSocket('ws://127.0.0.1:8888/ws');
        }else{
            alert('浏览器不支持WebSocket');
        }
        //设置点击事件
        $("#btn").click(function () {
            //发送消息给服务器
            websocket.send($("#message").val());
            $("#message").val("");
        });
        //接收服务器端消息
        websocket.onmessage = function () {
            let msg = event.data;
            console.log(msg);
            showMessage(msg);
        };
        //显示文字到弹幕上
        function showMessage(text) {
            $("#screen").append("<div style='color: azure'>" + text + "</div>")
        }
    </script>
</body>
</html>
